package com.cl.code.common.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author chengliang
 * @since 1.0.0
 */
public class NioFileUtils {

    /**
     * 读取文件内容
     *
     * @param pathname 文件路径
     * @return 文件内容
     * @throws IOException 读取异常
     */
    public static String readFileContent(String pathname) throws IOException {
        if (pathname == null) {
            throw new IOException("file path is null");
        }
        return readFileContent(Files.newInputStream(Paths.get(pathname)));
    }

    /**
     * 读取文件内容
     *
     * @param file 文件路径
     * @return 文件内容
     * @throws IOException 读取异常
     */
    public static String readFileContent(File file) throws IOException {
        if (file == null) {
            throw new IOException("file is null");
        }
        return readFileContent(Files.newInputStream(file.toPath()));
    }


    /**
     * 读取文件内容
     *
     * @param is 输入流
     * @return 文件内容
     * @throws IOException 读取异常
     */
    public static String readFileContent(InputStream is) throws IOException {
        try (ReadableByteChannel readableByteChannel = Channels.newChannel(is)) {
            return readFileContent(readableByteChannel);
        }
    }

    /**
     * 读取文件内容
     *
     * @param channel 通道
     * @return 文件内容
     * @throws IOException 读取异常
     */
    private static String readFileContent(ReadableByteChannel channel) throws IOException {
        // try with resources
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        StringBuilder sb = new StringBuilder();
        while (channel.read(buffer) != -1) {
            buffer.flip();
            while (buffer.hasRemaining()) {
                sb.append((char) buffer.get());
            }
            buffer.clear();
        }
        return sb.toString();
    }

    public static void writeFile(String pathname, byte[] bytes) throws IOException {
        try {
            Files.write(Paths.get(pathname), bytes);
        } catch (IOException e) {
            throw new IOException("write file failed", e);
        }
    }

    public static void writeFile(String pathname, String content) throws IOException {
        try {
            Files.write(Paths.get(pathname), content.getBytes());
        } catch (IOException e) {
            throw new IOException("write file failed", e);
        }
    }

    /**
     * 写文件
     *
     * @param pathname 文件路径
     * @param is       输入流
     * @throws IOException 写入异常
     */
    public static void writeFile(String pathname, InputStream is) throws IOException {
        try {
            Files.copy(is, Paths.get(pathname));
        } catch (IOException e) {
            throw new IOException("write file failed", e);
        }
    }

}
